//
//  KVHomeTableVC.swift
//  KVBestMicroblog
//
//  Created by 李康卫 on 16/7/18.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit
import SVPullToRefresh

class KVHomeTableVC: KVBaseTableViewController {
    
    let messageLabelHeight:CGFloat = 44

    let homeCell = "homeCell"
    //保存微博数组模型
    var statuses  = [KVStatuses]() {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置导航item的样式
        // MARK: - error
        if !KVUserAccountViewModel.sharedUserAccountViewModel.userIsLogin {
            return
        }
        self.tableView.registerClass(KVCustemHomeCell.self, forCellReuseIdentifier: homeCell)
        setupNavigationBarItem()
        //自定义naviewgationItem>titleView
//        昵称
        self.navigationItem.titleView = KVHomeTitleView(titleName: userName)
        
        //请求网络数据准备展示
        self.tableView.addSubview(pullDownReferesh)
        pullDownReferesh.refreshBlock = {
            self.loadMoreData()
          
        }
        //测试帧数
//        self.show(CGPoint(x: 300, y: 500))
        UIApplication.sharedApplication().keyWindow?.show(CGPoint(x: 200, y: 200))
        
        //画面开始就加载
        pullDownReferesh.beginRefreshing()
            //设置tableViewcell的属性
//        self.tableView.estimatedRowHeight = 200
        self.tableView.autoresizesSubviews = true
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
       
    }
    private func setupNavigationBarItem() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
    }
    private func loadMoreData() {
        let statusID = statuses.first?.id ?? 0
        KVStatusesViewModel.sharedStatuses.loadStatuses(statusID, max_id: 0) { (statuses, error) -> Void in
            if (error != nil) {
                print("网络加载出错\(error)")
                return
            }
            let count = statuses?.count
            if self.statuses.count == 0 {
                self.statuses = statuses!
                
//                print(statuses?.first?.created_at)
                //上拉加载更多
                self.tableView.addInfiniteScrollingWithActionHandler { () -> Void in
                    //加载更多以前数据
                    self.loadOldStatusData()
                    
                }
            } else {
                self.statuses = statuses! + self.statuses
            }
            
            self.pullDownReferesh.endRefreshing()
            //show
            self.showMessageLabel(count!)
        }
    }
    ///加载更多以前数据
    private func loadOldStatusData() {
        ///最低部的微博ID
        
        let lastStatusID: Int64 = self.statuses.last?.id ?? 0
        KVStatusesViewModel.sharedStatuses.loadStatuses(0, max_id: lastStatusID) { (statuses, error) -> Void in
            self.tableView.infiniteScrollingView.stopAnimating()    
            if error != nil {
                print("加载更多数据失败\(error)")
                return
            }
            //showMessage
            let count = statuses?.count
            self.showMessageLabel(count!)
            
            self.statuses = self.statuses + statuses!
        }
    }
    //消息框
    private func showMessageLabel(count: Int) {
        self.messageLabel.text = "加载了\(count)条微博"
        //判断动画的状态如果是相同的就不进行动画
        let key = messageLabel.layer.animationKeys()
        if key != nil {
            return
        }
        UIView.animateWithDuration(0.35) { () -> Void in
            self.messageLabel.transform = CGAffineTransformMakeTranslation(0, 64 + self.messageLabelHeight)
            UIView.animateWithDuration(0.35, delay: 1.25, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                self.messageLabel.transform = CGAffineTransformIdentity
                }, completion: nil)
        }
    }
  
    // MARK: -  点击事件
    @objc private func addPerson() {
        print("加人")
    }
    @objc private func popScan() {
        print("popScan")
    }
    // MARK: - 懒加载item
    
    private lazy var leftBtn: UIButton = {
       let leftBtn = UIButton()
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch"), forState: UIControlState.Normal)
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch_highlighted"), forState: UIControlState.Highlighted)
        leftBtn.sizeToFit()
        leftBtn.addTarget(self, action: "addPerson", forControlEvents: UIControlEvents.TouchUpInside)
        return leftBtn
    }()
    
    private lazy var rightBtn: UIButton = {
        let rightBtn = UIButton()
        rightBtn.setImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
        rightBtn.setImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted)
        rightBtn.sizeToFit()
        rightBtn.addTarget(self, action: "popScan", forControlEvents: UIControlEvents.TouchUpInside)
        return rightBtn
    }()
    //userName
    private lazy var userName: String = {
        let userName = KVUserAccountViewModel.sharedUserAccountViewModel.userAccount?.screen_name ?? "KVYouth"
        return userName
    }()
    //下拉刷新
    private lazy var pullDownReferesh: KVPullDownRefresh = KVPullDownRefresh()
    //加载提示框
    private lazy var messageLabel: UILabel = {
        let messageLabel = UILabel()
        messageLabel.text = "刷新了n条博"
        messageLabel.font = UIFont.systemFontOfSize(18)
        messageLabel.backgroundColor = UIColor.cyanColor()
        messageLabel.textAlignment = NSTextAlignment.Center
        messageLabel.frame = CGRectMake(0, -self.messageLabelHeight - 20, UIScreen.width(), self.messageLabelHeight)
        //添加到导航条
        self.navigationController?.navigationBar.insertSubview(messageLabel, atIndex: 0)

        return messageLabel
    }()

}

///实现tableView的代理方法 UITableViewDataSource
extension KVHomeTableVC {
 
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statuses.count ?? 0

    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(homeCell) as! KVCustemHomeCell
//        let cell = tableView.dequeueReusableCellWithIdentifier(homeCell, forIndexPath: indexPath) as! KVCustemHomeCell
        let status = self.statuses[indexPath.row]
        cell.status = status
//        cell.textLabel?.text = status.text
        return cell
    }
    //取消选中的高亮
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
//    设置tableView的高度
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let currentStatus = self.statuses[indexPath.row]
        let height = currentStatus.homestatusCellHieght
        return height!
    }
}
